package com.hxzy.common.web.controller;

import cn.hutool.core.lang.UUID;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.ServletUtils;
import com.hxzy.common.vo.PageVO;
import com.hxzy.common.vo.R;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;


/**
 * 通用控制器
 */
public class BaseController {



    protected R toR(int row){
        return  row>0? R.ok():  R.build(AckCode.FAIL);
    }

    protected  R toR(boolean result){
        return  result? R.ok():  R.build(AckCode.FAIL);
    }

    /**
     * 第页第三步，把Mybatis返回的结果IPage转换自定义的对象
     * @param page
     * @return
     */
    private static final String PAGE_NUM_NAME="page";

    private static final String PAGE_SIZE_NAME="size";

    /**
     * 启动pageHelper分页 PageHelper.startPage(1, 10);
     */
    protected void startPageHelper(){
        //当前第几页
        int page= ServletUtils.getParamsToInt(PAGE_NUM_NAME);
        //每页多少笔
        int size=ServletUtils.getParamsToInt(PAGE_SIZE_NAME);

        //使用pagehelper，开启mybatis分页拦截器
        PageHelper.startPage(page,size);
    }

    /**
     * 把pageHelper返回的Page对象转换成自已定义的对象
     * @param list
     * @return
     */
    protected R<PageVO>  pageToPageVO(List list){
        PageVO  pageVO=new PageVO();

        //mybatis分页插件
        if(list instanceof Page){
            Page  pg= (Page) list;
            pageVO.setTotal(pg.getTotal());
            pageVO.setRows(pg.getResult());
        }else{
            //普通的list
            pageVO.setRows(list);
            pageVO.setTotal(0L);
        }
        return  R.okHasData(pageVO);
    }

    /**
     * 把list变为分页的输出结果
     * @param list
     * @return
     */
    protected R listToPageVO(List list) {
        PageVO pageVo = new PageVO();
        pageVo.setTotal(0L);
        pageVo.setRows(list);
        return R.okHasData(pageVo);
    }


    protected <T> void writeExcel(HttpServletResponse response, String excelName, Class<T> tClass, List<T> data) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String chinaFileName=excelName+"_"+ UUID.fastUUID().toString()+".xlsx";

        String fileName = URLEncoder.encode(chinaFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName );

        //文件下载
        EasyExcel.write(response.getOutputStream(), tClass).sheet(excelName).doWrite(data );
    }



}
